﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XWG.JWBST.ProcessInterfaces;
using System.IO;
using System.Web;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using XWG.Framework.AuthUtility;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Converters;

namespace XWG.JWBST.AccidentProcess
{
    public class Process : IProcess
    {
        public string ProcessData(StreamReader reader, HttpContext context)
        {
            #region 变量声明
            string info = reader.ReadToEnd();
            info = HttpUtility.UrlDecode(info);
            JObject oka = (JObject)JsonConvert.DeserializeObject(info);
            string RequestType = oka["RequestType"].ToString().Replace("\"", string.Empty);
            BackContent Backcontent = new BackContent();
            BackList bcList = new BackList();
            ResultModel re = new ResultModel();
            string RetrunMes = string.Empty;
            int reContent = -1;  //返回标志 当为1的时候返回数据格式为数组 
            #endregion


            #region 获取流水号
            if (RequestType == "RequestLSH")
            {
                string lshnum = XWG.JWBST.JWBSTBLL.TbBstFastprocessBLL.GetLSH("TB_BST_FASTPROCESS");
                if (!string.IsNullOrEmpty(lshnum))
                {
                    Backcontent.Status = 100;
                    Backcontent.Content = lshnum;
                }
                else
                {
                    Backcontent.Status = -100;
                    Backcontent.Content = "操作失败！无法获取流水号";
                }
            }
            #endregion

            #region 上传地址信息
            else if (RequestType == "UploadArea")
            {
                try
                {
                    XWG.JWBST.JWBSTEntity.TbBstFastprocess accidentInfo = new JWBSTEntity.TbBstFastprocess();
                    Dictionary<string, object> dic = JsonToDictionary(info);//将Json数据转成dictionary格式
                    Dictionary<string, object> dataSet = (Dictionary<string, object>)dic;
                    foreach (KeyValuePair<string, object> item in dataSet)
                    {
                        if (item.Key.ToString() == "DeviceToken")//获取header数据
                        {
                            accidentInfo.FastToken = oka["DeviceToken"].ToString().Replace("\"", string.Empty);
                            break;
                        }
                        else
                        {
                            accidentInfo.FastToken = string.Empty;
                        }
                    }

                    accidentInfo.FastId = Guid.NewGuid().ToString();
                    accidentInfo.FastLsh = oka["Lsh"].ToString().Replace("\"", string.Empty);
                    accidentInfo.FastAddress = oka["Address"].ToString().Replace("\"", string.Empty);
                    accidentInfo.FastMark = oka["Mark"].ToString().Replace("\"", string.Empty); //数据来源  0为济南民生警务手机端提交  1为101车主服务上传
                    accidentInfo.FastUptime = DateTime.Now;
                    accidentInfo.FastAuditstatus = "0";
                    accidentInfo.FastDel = "0";
                    accidentInfo.FastComplete = "0";
                    accidentInfo.FastIspolice = "0";


                    re = XWG.JWBST.JWBSTBLL.TbBstFastprocessBLL.Insert(accidentInfo, "", false);
                    if (re.ISSucceed)
                    {
                        Backcontent.Status = 100;
                        Backcontent.Content = re.FiledKey;
                    }
                    else
                    {
                        Backcontent.Status = -100;
                        Backcontent.Content = "操作失败！错误代码:" + re.ErrorCode.ToString();
                    }
                }
                catch (Exception ex)
                {
                    Backcontent.Status = -112;
                    Backcontent.Content = "操作失败！错误信息：" + ex.Message;
                }
            }
            #endregion

            #region 上传基本信息
            else if (RequestType == "UploadInfo")   //上传基本信息
            {
                try
                {
                    string FastId = oka["ID"].ToString().Replace("\"", string.Empty);
                    var GetInfo = XWG.JWBST.JWBSTBLL.TbBstFastprocessBLL.Load(FastId);
                    GetInfo.FastId = FastId;
                    GetInfo.FastPhonea = oka["Phone_A"].ToString().Replace("\"", string.Empty);
                    if (string.IsNullOrEmpty(oka["Phone_B"].ToString().Replace("\"", string.Empty)))
                    {

                    }
                    else
                    {
                        GetInfo.FastPhoneb = oka["Phone_B"].ToString().Replace("\"", string.Empty);
                    }
                    GetInfo.FastLpna = oka["CarMine"].ToString().Replace("\"", string.Empty);
                    GetInfo.FastLpnb = oka["CarOther"].ToString().Replace("\"", string.Empty);
                    GetInfo.FastGpsJd = oka["GPS_JD"].ToString().Replace("\"", string.Empty);
                    GetInfo.FastGpsWd = oka["GPS_WD"].ToString().Replace("\"", string.Empty);
                    GetInfo.FastComplete = "1";

                    if (GetInfo.FastMark == "1")
                    {
                        //注册操作
                    }
                    //记录请求信息
                    JWBSTEntity.TbBstVisits visit = new JWBSTEntity.TbBstVisits();
                    visit.Id = Guid.NewGuid().ToString();
                    visit.Phone = GetInfo.FastPhonea;
                    visit.Time = DateTime.Now;
                    visit.Modulename = "Kckp";
                    visit.Optionname = "快处快赔基本信息上传";
                    visit.Other = oka.ToString();
                    JWBSTBLL.TbBstVisitsBLL.Insert(visit, "", false);
                    re = XWG.JWBST.JWBSTBLL.TbBstFastprocessBLL.Update(GetInfo, "", false);
                    if (re.ISSucceed)
                    {
                        Backcontent.Status = 100;
                        Backcontent.Content = "操作成功！";
                    }
                    else
                    {
                        Backcontent.Status = -100;
                        Backcontent.Content = "操作失败！错误代码" + re.ErrorCode.ToString();
                    }
                }
                catch (Exception ex)
                {
                    Backcontent.Status = -112;
                    Backcontent.Content = "操作失败！错误信息：" + ex.Message;
                }
            }
            #endregion

            #region 根据手机号获取历史列表
            else if (RequestType == "HistoryList")
            {

                try
                {
                    //根据手机号请求历史列表
                    string Phone = oka["Phone"].ToString().Replace("\"", string.Empty);
                    List<HistoryList> HList = new List<HistoryList>();
                    List<XWG.JWBST.JWBSTEntity.TbBstFastprocess> fastList = new List<JWBSTEntity.TbBstFastprocess>();
                    fastList = XWG.JWBST.JWBSTBLL.TbBstFastprocessBLL.GetInfoByPhone(Phone);
                    if (fastList.Count == 0)
                    {
                        Backcontent.Status = 100;
                        Backcontent.Content = "暂无该手机号报案记录";
                    }
                    else
                    {
                        for (int i = 0; i < fastList.Count; i++)
                        {
                            HistoryList His = new HistoryList();
                            His.Title = fastList[i].FastLsh;
                            His.Address = fastList[i].FastAddress;
                            if (fastList[i].FastAuditstatus == "未审核")
                            {
                                His.Auditstatus = "未审核";

                                His.Auditresult = "该事故尚未审核";
                            }
                            else
                            {
                                His.Auditstatus = "已审核";
                                His.Auditresult = fastList[i].FastAuditresult;

                            }
                            HList.Add(His);
                        }
                        bcList.Status = 100;
                        bcList.list = HList;
                        reContent = 1;
                    }
                }
                catch (Exception ex)
                {
                    Backcontent.Status = -112;
                    Backcontent.Content = "操作失败！错误信息：" + ex.Message;
                }
            }
            #endregion

            #region 根据事故流水号获取详细历史
            else if (RequestType == "HistoryInfo")
            {
                //根据事故流水号请求详细历史
                try
                {
                    string LSH = oka["LSH"].ToString().Replace("\"", string.Empty);
                    XWG.JWBST.JWBSTEntity.TbBstFastprocess fastinfo = new JWBSTEntity.TbBstFastprocess();
                    History fasthis = new History();
                    fastinfo = XWG.JWBST.JWBSTBLL.TbBstFastprocessBLL.GetAduitByLSH(LSH);
                    if (fastinfo == null)
                    {
                        Backcontent.Status = -100;
                        Backcontent.Content = "获取信息失败";
                    }
                    else
                    {
                        fasthis.Title = fastinfo.FastLsh;
                        fasthis.Address = fastinfo.FastAddress;
                        fasthis.LPNa = fastinfo.FastLpna;
                        fasthis.LPNb = fastinfo.FastLpnb;
                        fasthis.Phonea = fastinfo.FastPhonea;
                        fasthis.Phoneb = fastinfo.FastPhoneb;
                        if (fastinfo.FastAuditstatus == "未审核")
                        {
                            fasthis.Auditstatus = "未审核";
                            fasthis.Auditresult = "该事故尚未审核";
                            fasthis.Audittime = "该事故尚未审核";
                        }
                        else
                        {
                            fasthis.Auditstatus = "已审核";
                            fasthis.Auditresult = fastinfo.FastAuditresult;
                            fasthis.Audittime = fastinfo.FastAudittime.ToString();
                        }
                        fasthis.UpTime = fastinfo.FastUptime.ToString();
                        IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                        Backcontent.Status = 100;
                        Backcontent.Content = JsonConvert.SerializeObject(fasthis, dtConverter);
                    }
                }
                catch (Exception ex)
                {
                    Backcontent.Status = -112;
                    Backcontent.Content = "操作失败！错误代码" + ex.Message;
                }
            }
            #endregion

            #region 错误请求
            else
            {
                Backcontent.Status = -112;
                Backcontent.Content = "错误的请求信息";
            }
            #endregion

            if (reContent == 1)
            {
                RetrunMes = JsonConvert.SerializeObject(bcList);
            }
            else
            {
                RetrunMes = JsonConvert.SerializeObject(Backcontent); 
            }
            return RetrunMes;
        }

        #region 返回类
        /// <summary>
        /// 返回数据
        /// </summary>
        public class BackContent
        {
            public int Status { get; set; }
            public string Content { get; set; }
        }

        public class BackList
        {
            public int Status { get; set; }
            public List<HistoryList> list { get; set; }
        }

        /// <summary>
        /// 事故快处历史列表
        /// </summary>
        public class HistoryList
        {
            public string Title { get; set; }
            public string Address { get; set; }
            public string Auditstatus { get; set; }
            public string Auditresult { get; set; }
        }

        /// <summary>
        /// 事故快处详细
        /// </summary>
        public class History
        {
            public string Title { get; set; }
            public string Phonea { get; set; }
            public string Phoneb { get; set; }
            public string LPNa { get; set; }
            public string LPNb { get; set; }
            public string UpTime { get; set; }
            public string Address { get; set; }
            public string Audittime { get; set; }
            public string Auditresult { get; set; }
            public string Auditstatus { get; set; }
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 将json数据反序列化为Dictionary
        /// </summary>
        /// <param name="jsonData">json数据</param>
        /// <returns></returns>
        private Dictionary<string, object> JsonToDictionary(string jsonData)
        {
            //实例化JavaScriptSerializer类的新实例
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
                return jss.Deserialize<Dictionary<string, object>>(jsonData);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion
    }
}
